<template>
  <el-card>
    <el-form :inline="true" class="demo-form-inline">
     

      <el-form-item>
                  <el-form-item>
            <el-cascader
              v-model="from.DepetmentId"
              :options="options"
              :props="props1"
              placeholder="请选择科室"
              class="search-select"
            />
          </el-form-item>
      </el-form-item>

      <el-form-item>
        <el-input v-model="from.DoctorName" placeholder="请输入医生姓名" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="DoctorShow()">搜索</el-button>
      </el-form-item>

       

    </el-form>

  </el-card>

  <el-card>
    <div class="table-header">
      <div class="week-navigation">
        <el-button :icon="ArrowLeft" @click="previousWeek">上一周</el-button>
        <span class="week-range">{{ weekRangeText }}</span>
        <el-button :icon="ArrowRight" @click="nextWeek">下一周</el-button>
        <el-button @click="goToCurrentWeek" type="primary" plain>本周</el-button>
      </div>
      <el-button type="primary" :icon="Plus" @click="open(null)" >新增医生排班信息</el-button>
    </div>
    <el-table :data="rowData" border style="width: 100%">
      <el-table-column prop="doctorName" label="医生姓名" width="90" />
      <el-table-column prop="departmentName" label="科室" width="90" />

      <el-table-column v-for="day in weekDays" :key="dayKey(day)" :label="dateLabel(day)">
        <el-table-column label="上午" width="120">
          <template #default="{ row }">
            <div class="session-cell" @click="openSetScheduleFromTable(row, day, 0)">
              <template v-if="status(row, day, 0).type === 'rest'">
                <el-tag type="info" size="small" effect="plain"> 
                  <el-icon><Minus /></el-icon>
                  休
                </el-tag>
              </template>
              <template v-else-if="status(row, day, 0).type === 'available'">
                <el-tag type="success" size="small" effect="plain">
                  <el-icon><CircleCheckFilled /></el-icon>
                  可预约
                </el-tag>
                <span class="num am-has">{{ status(row, day, 0).text }}</span>
              </template>
              <template v-else> 
                <el-tag type="danger" size="small" effect="plain">
                  <el-icon><CircleCloseFilled /></el-icon>
                  已满
                </el-tag>
                <span class="num am-full">{{ status(row, day, 0).text }}</span>
              </template>
              <!-- 多条记录时显示选择器 -->
              <div v-if="hasMultipleRecords(row, day, 0)" class="record-selector" @click.stop>
                <el-select 
                  v-model="selectedRecords[getRecordKey(row, day, 0)]" 
                  size="small" 
                  placeholder="选择记录"
                  @change="onRecordChange(row, day, 0, $event)"
                >
                  <el-option 
                    v-for="(record, index) in getAllRecords(row, day, 0)" 
                    :key="record.schedulingId || record.SchedulingId || index"
                    :label="getRecordLabel(record)" 
                    :value="record.schedulingId || record.SchedulingId || index"
                  />
                </el-select>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下午" width="120">
          <template #default="{ row }">
            <div class="session-cell" @click="openSetScheduleFromTable(row, day, 1)">
              <template v-if="status(row, day, 1).type === 'rest'">
                <el-tag type="info" size="small" effect="plain">
                  <el-icon><Minus /></el-icon>
                  休
                </el-tag>
              </template>
              <template v-else-if="status(row, day, 1).type === 'available'">
                <el-tag type="success" size="small" effect="plain">
                  <el-icon><CircleCheckFilled /></el-icon>
                  可预约
                </el-tag>
                <span class="num am-has">{{ status(row, day, 1).text }}</span>
              </template>
              <template v-else>
                <el-tag type="danger" size="small" effect="plain">
                  <el-icon><CircleCloseFilled /></el-icon>
                  已满
                </el-tag>
                <span class="num am-full">{{ status(row, day, 1).text }}</span>
              </template>
              <!-- 多条记录时显示选择器 -->
              <div v-if="hasMultipleRecords(row, day, 1)" class="record-selector" @click.stop>
                <el-select 
                  v-model="selectedRecords[getRecordKey(row, day, 1)]" 
                  size="small" 
                  placeholder="选择记录"
                  @change="onRecordChange(row, day, 1, $event)"
                >
                  <el-option 
                    v-for="(record, index) in getAllRecords(row, day, 1)" 
                    :key="record.schedulingId || record.SchedulingId || index"
                    :label="getRecordLabel(record)" 
                    :value="record.schedulingId || record.SchedulingId || index"
                  />
                </el-select>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column>
        <template #default="{ row }">
          <el-button :icon="Setting" circle type="primary" @click="openSetSchedule(row)" />
        </template>
      </el-table-column>

      
    
    </el-table>

    

      <!-- 排班添加修改弹框 -->
       <el-dialog v-model="logic.isopen" :title="logic.title" width="500" draggable>
    <el-form :model="form">
      <el-form-item label="医生">
         <el-select v-model="form.doctorId">
          <el-option v-for="a  in doctor" :label="a.doctorName" :value="a.doctorId"></el-option>
        </el-select>
      </el-form-item>

    <el-form-item label="所属科室" prop="departmentId">
      <el-cascader
        v-model="form.depetmentId"
        :options="options"
        :props="props1"
      />
    </el-form-item>


      <el-form-item label="开始时间">
      
    <div class="block">
      <el-date-picker
        v-model="form.startDate"
        type="datetime"
        placeholder="请选择开始时间"
        format="YYYY-MM-DD HH:mm:ss"
        date-format="MMM DD, YYYY"
        time-format="HH:mm"
      />
    </div>
      </el-form-item>



       <el-form-item label="接诊时间">
      
    <div class="block">
      <el-date-picker
        v-model="form.consultationTime"
        type="datetime"
        placeholder="请选择接诊时间"
        format="YYYY-MM-DD HH:mm:ss"
        date-format="MMM DD, YYYY"
        time-format="HH:mm"
      />
    </div>
      </el-form-item>



      <el-form-item label="号源数">
        <el-input-number v-model="form.num" :min="1" @change="handleChange" />
      </el-form-item>



      <el-form-item label="就诊人数">
       <el-input-number v-model="form.patientNum" :min="0" @change="handleChange" />
      </el-form-item>
    



      <el-form-item label="状态">
        <el-radio-group v-model="form.schedulingState">
      <el-radio :value="0" size="large">休</el-radio>
      <el-radio :value="1" size="large">上班</el-radio>
    </el-radio-group>
        
       
      </el-form-item>

      <el-form-item label="上午/下午">
        <el-select v-model="form.session">
           <el-option label="请选择" :value="0" />
          <el-option label="上午" :value="1" />
          <el-option label="下午" :value="2" />
        </el-select>
             
      </el-form-item>

      <el-form-item>
       <el-button type="primary" @click="save()">保存</el-button>
      <el-button default @click="logic.isopen=false">取消</el-button>
      </el-form-item>
   </el-form>
  </el-dialog>

   
    <!-- 排班详情弹窗 -->
    <el-dialog v-model="dialogVisible" width="920px" class="schedule-dialog" :close-on-click-modal="false" title="医生排班详情">
      <div class="dialog-body">
        <div class="dialog-left">
          <div class="doctor-title">{{ selectedDoctorRow?.doctorName }}医生排班详情</div>
          <div class="date-title">{{ formatSelectedDate(selectedDate) }}</div>
          <div class="weekday">{{ weekdayLabel(selectedDate) }}</div>
          <el-divider />
          <div class="section">
            <div class="section-title">上午</div>
            
              <div class="kv">接诊时间：{{ timeText(0) }}</div>
            <div class="kv">号源数：{{ sessionNum(0) }}</div>
            <div class="kv">接诊人数：{{ sessionBooked(0) }}</div>
            
          </div>
          <el-divider />
          <div class="section">
            <div class="section-title">下午</div>
            <div class="kv">接诊时间：{{ timeText(1) }}</div>
            <div class="kv">号源数：{{ sessionNum(1) }}</div>
            <div class="kv">接诊人数：{{ sessionBooked(1) }}</div>
          </div>
        </div>
        <div class="dialog-right">
          <div class="top-actions">
            <el-date-picker v-model="currentMonth" type="month" placeholder="请选择月份" format="YYYY年MM月" value-format="YYYY-MM" />
            <div class="flex-spacer"></div>
            <el-button type="primary" @click="submitSetSchedule">设置排班</el-button>
            <el-button @click="submitCloseBooking">关闭预约</el-button>
          </div>
          <div class="month-grid">
            <div v-for="d in monthDays" :key="d.date" class="grid-day" :class="[d.type, selectedDate === d.date ? 'selected' : '']" @click="selectDate(d.date)">
              <div class="day-num">{{ d.day }}</div>
              <div class="day-label">{{ d.label }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 分页 -->
       <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
    />
  </el-card>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { onMounted, reactive, ref, computed, watch } from 'vue'
import moment from 'moment'
import { useRouter } from 'vue-router'
import 'moment/locale/zh-cn'
import { Plus, Edit, Search, Share, Upload } from '@element-plus/icons-vue'

import { Setting, CircleCheckFilled, CircleCloseFilled, Minus, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, ElSkeleton } from 'element-plus'
import router from '@/router'
import { dataRead } from '@/Utils/Http'

const handleChange = (value: number | undefined) => {
  console.log(value)
}

moment.locale('zh-cn')

// 原始排班数据（后端返回的列表）
const tableData = ref<any[]>([])
const total = ref(0)

// 当前显示的周（ISO周）
const currentWeek = ref(moment().startOf('isoWeek'))

// 存储用户选择的记录
const selectedRecords = ref<Record<string, any>>({})


//弹出对话框参数
const logic=reactive({
isopen:false,
isadd:false,
title:'',
})


//添加修改参数
const form = reactive({
  schedulingId:0,
  doctorId:'',
  depetmentId:0,
  startDate:'',
  consultationTime: '',
  num:0,
  patientNum: 0,
  schedulingState:0,
  session: 0,
})

//打开添加修改
const open=(row:any)=>{
  logic.isopen=true
  if(row==null)
{
  logic.isadd=true,
  logic.title='添加医生排班信息';
  form.schedulingId=0,
  form.doctorId='',
  form.depetmentId=0,
  form.startDate='',
  form.consultationTime='',
  form.num=0,
  form.patientNum=0,
  form.schedulingState=0,
  form.session=0;
}
else
{
  // 修改模式 - 数据已经在submitSetSchedule中反填
  logic.isadd=false,
  logic.title='修改医生排班信息';
}


}

//添加修改方法
const save=()=>{
if(logic.isadd==true)
{
axios.post("http://localhost:5250/api/DoctorSchduling/AddDoctorSchduling",form).then(res=>{
if(res.data.code==300)
{
  ElMessage.success(res.data.message);
  logic.isopen=false;
  DoctorShow();

}
else
{
  ElMessage.error(res.data.message);
}

})

}
else
{
// 修改排班信息
axios.put("http://localhost:5250/api/DoctorSchduling/UpdDoctorScheduling",form).then(res=>{
if(res.data.code==400)
{
  ElMessage.success(res.data.message);
  logic.isopen=false;
  DoctorShow();
}
else
{
  ElMessage.error(res.data.message);
}
})
}

}


// 动态计算显示日期（基于当前选择的周）
const weekDays = computed(() => {
  return Array.from({ length: 7 }, (_, i) => 
    currentWeek.value.clone().add(i, 'days').toDate()
  )
})

// 周范围显示文本
const weekRangeText = computed(() => {
  const start = currentWeek.value.format('MM/DD')
  const end = currentWeek.value.clone().add(6, 'days').format('MM/DD')
  return `${start} - ${end}`
})

function dayKey(day: Date) {
  return moment(day).format('YYYY-MM-DD')
}
function dateLabel(day: Date) {
  const weekMap = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  const idx = moment(day).isoWeekday() - 1
  return `${moment(day).format('YYYY/MM/DD')} ${weekMap[idx]}`
}

// 周切换方法
function previousWeek() {
  currentWeek.value = currentWeek.value.clone().subtract(1, 'week')
  DoctorShow() // 重新获取数据
}

function nextWeek() {
  currentWeek.value = currentWeek.value.clone().add(1, 'week')
  DoctorShow() // 重新获取数据
}

function goToCurrentWeek() {
  currentWeek.value = moment().startOf('isoWeek')
  DoctorShow() // 重新获取数据
}



//钩子函数
onMounted(() => {
  DoctorShow()
  fetchDepartments();
  ShowDoctor();
})


// 医生排班的显示
function DoctorShow() {
  // 计算当前周的日期范围
  const weekStart = currentWeek.value.format('YYYY-MM-DD')
  const weekEnd = currentWeek.value.clone().add(6, 'days').format('YYYY-MM-DD')
  
  axios
    .get('http://localhost:5103/api/DoctorScheduling/ShowDoctorScheduling', {
      params: {
        PageIndex: page.PageIndex,
        PageSize: page.PageSize,
        DoctorName: from.DoctorName,
        DepetmentId: from.DepetmentId,
        WeekStart: weekStart,
        WeekEnd: weekEnd,
      },
    })
    .then((res) => {
      if (res.data?.code === 200) {
        tableData.value=res.data.data.data;
        page.pageCount=res.data.data.pageCount;
        page.totalCount=res.data.data.totalCount;
        
        
      }
    })
    .catch(() => {
      tableData.value = []
      total.value = 0
    })
}

//查询一条数据
const GetDoctorScheduling = async (schedulingId: any) => {
  try {
    const res = await axios.get('http://localhost:5103/api/DoctorScheduling/GetDoctorScheduling', {
      params: { schedulingId },
    })
    const data = res.data?.data ?? res.data
    const item = Array.isArray(data) ? data[0] : data
    if (item) {
      // 计算日期并更新当前选择
      const ct = item.consultationTime ?? item.ConsultationTime
      const dateKey = ct ? moment(ct).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD')
      
      // 写入弹窗的当日 AM/PM 数据
      const map = { ...dialogSchedules.value }
      pushToDialogMap(map, item)
      dialogSchedules.value = map
    }
  } catch (e) {
    console.error('GetDoctorScheduling 请求失败', e)
  }
}


// 将后端列表按医生分组，供表格使用
const rowData = computed(() => {
  const map = new Map<string | number, any>()
  for (const item of tableData.value) {
    const doctorId = item.doctorId ?? item.DoctorId ?? item.doctorID
    if (!doctorId) continue
    if (!map.has(doctorId)) {
      map.set(doctorId, {
        doctorId,
        doctorName: item.doctorName ?? item.DoctorName,
        departmentName: item.departmentName ?? item.DepetmentName ?? '',
        schedules: {} as Record<string, { am?: any; pm?: any }>,
        allSchedules: {} as Record<string, { am?: any[]; pm?: any[] }>, // 存储所有记录
      })
    }
    const row = map.get(doctorId)
    const dateKey = moment(item.consultationTime ?? item.ConsultationTime).format('YYYY-MM-DD')
    // 根据 consultationTime 动态判断上午(0)/下午(1)
    const dt = item.consultationTime ?? item.ConsultationTime
    const sessionFromTime: 0 | 1 = dt ? (moment(dt).hour() < 12 ? 0 : 1) : 0
    const sessionRaw = item.session ?? item.Session
    const session: 0 | 1 = (sessionRaw === undefined || sessionRaw === null)
      ? sessionFromTime
      : ((sessionRaw === 0 || sessionRaw === 1) ? sessionRaw : sessionFromTime)
    
    // 初始化数据结构
    row.schedules[dateKey] = row.schedules[dateKey] || {}
    row.allSchedules[dateKey] = row.allSchedules[dateKey] || { am: [], pm: [] }
    
    // 存储所有记录
    if (session === 0) {
      row.allSchedules[dateKey].am.push(item)
    } else {
      row.allSchedules[dateKey].pm.push(item)
    }
    
    // 选择最佳记录作为显示记录（优先选择状态为上班的记录）
    const currentRecords = session === 0 ? row.allSchedules[dateKey].am : row.allSchedules[dateKey].pm
    const bestRecord = selectBestRecord(currentRecords)
    
    if (session === 0) {
      row.schedules[dateKey].am = bestRecord
    } else {
      row.schedules[dateKey].pm = bestRecord
    }
  }
  return Array.from(map.values())
})

// 选择最佳记录的函数
function selectBestRecord(records: any[]): any {
  if (!records || records.length === 0) return null
  if (records.length === 1) return records[0]
  
  // 优先选择状态为上班(1)的记录
  const workingRecords = records.filter(r => (r.schedulingState ?? r.SchedulingState) === 1)
  if (workingRecords.length > 0) {
    // 如果有多个上班记录，选择最新的（按schedulingId排序）
    return workingRecords.sort((a, b) => (b.schedulingId ?? b.SchedulingId) - (a.schedulingId ?? a.SchedulingId))[0]
  }
  
  // 如果没有上班记录，选择最新的记录
  return records.sort((a, b) => (b.schedulingId ?? b.SchedulingId) - (a.schedulingId ?? a.SchedulingId))[0]
}

function getItem(row: any, day: Date, session: 0 | 1) {
  const dateKey = dayKey(day)
  const slot = row.schedules?.[dateKey]
  return session === 0 ? slot?.am : slot?.pm
}

function getItemByDateStr(row: any, dateKey: string, session: 0 | 1) {
  const slot = row.schedules?.[dateKey]
  return session === 0 ? slot?.am : slot?.pm
}

// 检查是否有多个记录
function hasMultipleRecords(row: any, day: Date, session: 0 | 1): boolean {
  const dateKey = dayKey(day)
  const records = session === 0 ? row.allSchedules?.[dateKey]?.am : row.allSchedules?.[dateKey]?.pm
  return records && records.length > 1
}

// 获取所有记录
function getAllRecords(row: any, day: Date, session: 0 | 1): any[] {
  const dateKey = dayKey(day)
  const records = session === 0 ? row.allSchedules?.[dateKey]?.am : row.allSchedules?.[dateKey]?.pm
  return records || []
}

// 生成记录的唯一键
function getRecordKey(row: any, day: Date, session: 0 | 1): string {
  const dateKey = dayKey(day)
  return `${row.doctorId}_${dateKey}_${session}`
}

// 获取记录标签
function getRecordLabel(record: any): string {
  const state = record.schedulingState ?? record.SchedulingState
  const stateText = state === 1 ? '上班' : '休息'
  const time = record.consultationTime ?? record.ConsultationTime
  const timeText = time ? moment(time).format('HH:mm') : ''
  const num = record.num ?? record.Num ?? 0
  const patientNum = record.patientNum ?? record.PatientNum ?? 0
  
  return `${stateText} ${timeText} (${patientNum}/${num})`
}

// 记录选择变化处理
function onRecordChange(row: any, day: Date, session: 0 | 1, selectedId: any) {
  const dateKey = dayKey(day)
  const records = getAllRecords(row, day, session)
  const selectedRecord = records.find(r => 
    (r.schedulingId ?? r.SchedulingId) === selectedId
  )
  
  if (selectedRecord) {
    // 更新显示的记录
    if (session === 0) {
      row.schedules[dateKey].am = selectedRecord
    } else {
      row.schedules[dateKey].pm = selectedRecord
    }
  }
}

function status(row: any, day: Date, session: 0 | 1) {
  const item = getItem(row, day, session)
  if (!item) return { type: 'rest', text: '休' }
  const state = item.schedulingState ?? item.SchedulingState
  const booked = item.patientNum ?? item.PatientNum ?? 0
  const capacity = item.num ?? item.Num ?? 0
  if (state === 0) return { type: 'rest', text: '休' }
  if (capacity > 0 && booked >= capacity) return { type: 'full', text: `${booked}/${capacity}` }
  return { type: 'available', text: `${booked}/${capacity}` }
}


const currentMonth = ref<string>(moment().format('YYYY-MM'))
const dialogVisible = ref(false)
const selectedDoctorRow = ref<any | null>(null)
const selectedDate = ref<string>(moment().format('YYYY-MM-DD'))
// 弹窗内使用的排班数据（优先显示），键为 YYYY-MM-DD，值为 { am, pm }
const dialogSchedules = ref<Record<string, { am?: any; pm?: any }>>({})


// 定义 updatefrom 变量
const updatefrom = reactive({
  consultationTime: '',
  num: 0,
  patientNum: 0
})

// 选出医生首个有排班日期（AM/PM 任一存在即返回）
function firstAvailableDate(row: any): string | null {
  if (!row?.schedules) return null
  const dates = Object.keys(row.schedules).sort()
  for (const d of dates) {
    const slot = row.schedules[d]
    if (slot?.am || slot?.pm) return d
  }
  return null
}

function openSetSchedule(row?: any) {
  selectedDoctorRow.value = row || rowData.value[0] || null
  if (!selectedDoctorRow.value) return
  const firstDate = firstAvailableDate(selectedDoctorRow.value)
  if (firstDate) {
    selectedDate.value = firstDate
    currentMonth.value = moment(firstDate, 'YYYY-MM-DD').format('YYYY-MM')
  } else {
    const today = moment()
    const m = moment(currentMonth.value, 'YYYY-MM')
    selectedDate.value = m.isSame(today, 'month') ? today.format('YYYY-MM-DD') : m.startOf('month').format('YYYY-MM-DD')
  }
  dialogVisible.value = true
  fetchSelectedDateDetail()
}




// 依据 consultationTime 判定 session，并按天聚合
function pushToDialogMap(map: Record<string, { am?: any; pm?: any }>, item: any) {
  const dateKey = moment(item.consultationTime ?? item.ConsultationTime).format('YYYY-MM-DD')
  const dt = item.consultationTime ?? item.ConsultationTime
  const sessionFromTime: 0 | 1 = dt ? (moment(dt).hour() < 12 ? 0 : 1) : 0
  const sessionRaw = item.session ?? item.Session
  const session: 0 | 1 = (sessionRaw === undefined || sessionRaw === null)
    ? sessionFromTime
    : ((sessionRaw === 0 || sessionRaw === 1) ? sessionRaw : sessionFromTime)
  map[dateKey] = map[dateKey] || {}
  if (session === 0) map[dateKey].am = item
  else map[dateKey].pm = item
}



function getDaySessions(row: any, dateKey: string) {
  // 弹窗优先使用后端接口数据，其次回退到列表聚合
  const slotFromApi = dialogSchedules.value[dateKey]
  if (slotFromApi) return { am: (slotFromApi as any).am, pm: (slotFromApi as any).pm }
  const slotFromTable = (row && row.schedules && row.schedules[dateKey]) ? row.schedules[dateKey] : {}
  return { am: (slotFromTable as any).am, pm: (slotFromTable as any).pm }
}

// 切换月份时仅更新日历视图，不发起请求
watch(currentMonth, () => {
  // 不再需要在此处调用 fetchDialogSchedules
})

function daySummary(row: any, dateKey: string) {
  const { am, pm } = getDaySessions(row, dateKey)
  const isRest = (s: any) => (s && ((s.schedulingState ?? s.SchedulingState) === 1))
  const cap = (s: any) => s ? (s.num ?? s.Num ?? 0) : 0
  const booked = (s: any) => s ? (s.patientNum ?? s.PatientNum ?? 0) : 0
  if (!am && !pm) return { type: 'none', label: '未排班' }
  if (isRest(am) && isRest(pm)) return { type: 'rest', label: '休息' }
  const totalCap = cap(am) + cap(pm)
  const totalBooked = booked(am) + booked(pm)
  if (totalCap > 0) return { type: 'open', label: `号源 ${totalCap}` }
  if (totalBooked > 0) return { type: 'visit', label: `接诊 ${totalBooked}` }
  return { type: 'none', label: '未排班' }
}

const monthDays = computed(() => {
  const arr: Array<{ date: string; day: number; label: string; type: string }> = []
  if (!selectedDoctorRow.value) return arr
  const m = moment(currentMonth.value, 'YYYY-MM')
  const start = m.startOf('month').clone()
  const end = m.endOf('month').clone()
  const cur = start.clone()
  while (cur.isSameOrBefore(end, 'day')) {
    const dateKey = cur.format('YYYY-MM-DD')
    const s = daySummary(selectedDoctorRow.value, dateKey)
    arr.push({ date: dateKey, day: cur.date(), label: s.label, type: s.type })
    cur.add(1, 'day')
  }
  return arr
})

function selectDate(dateKey: string) {
  selectedDate.value = dateKey
  fetchSelectedDateDetail()
}

function formatSelectedDate(dateKey: string) {
  return moment(dateKey, 'YYYY-MM-DD').format('YYYY年M月D日')
}
function weekdayLabel(dateKey: string) {
  const idx = moment(dateKey, 'YYYY-MM-DD').isoWeekday() - 1
  const map = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  return map[idx]
}



// 选择某天的优先项（先 AM 再 PM），仅使用现有字段
function getPreferredItemForDate(row: any, dateKey: string): any | null {
  const slot = (row && row.schedules && row.schedules[dateKey]) ? row.schedules[dateKey] : null
  return slot ? (slot.am || slot.pm || null) : null
}

// 左侧显示函数：全部使用 consultationTime/num/patientNum（你的字段）
function timeText(session: 0 | 1) {
  const fromApi = dialogSchedules.value[selectedDate.value]
  let realItem: any | undefined = fromApi ? (session === 0 ? fromApi.am : fromApi.pm) : undefined
  if (!realItem && selectedDoctorRow.value) realItem = getItemByDateStr(selectedDoctorRow.value, selectedDate.value, session) as any
  
  // 根据 session 字段判断时间段
  const itemSession = realItem ? realItem.session : undefined
  if (itemSession !== undefined) {
    // 如果 session 字段存在，直接根据它判断
    return itemSession === 0 ? '08:00-12:00' : '14:00-18:00'
  } else {
    // 如果没有 session 字段，根据 consultationTime 的时间判断
    const ct = realItem ? realItem.consultationTime : updatefrom.consultationTime
    if (ct) {
      const hour = moment(ct).hour()
      return hour < 12 ? '08:00-12:00' : '14:00-18:00'
    }
  }
  
  // 默认显示
  return session === 0 ? '08:00-12:00' : '14:00-18:00'
}
function sessionNum(session: 0 | 1) {
  const fromApi = dialogSchedules.value[selectedDate.value]
  let realItem: any | undefined = fromApi ? (session === 0 ? fromApi.am : fromApi.pm) : undefined
  if (!realItem && selectedDoctorRow.value) realItem = getItemByDateStr(selectedDoctorRow.value, selectedDate.value, session) as any

  // 无论上午还是下午，都使用 num 字段显示号源数
  const val = realItem ? realItem.num : undefined
  return val !== undefined ? val : updatefrom.num || 0
}
function sessionBooked(session: 0 | 1) {
  const fromApi = dialogSchedules.value[selectedDate.value]
  let realItem: any | undefined = fromApi ? (session === 0 ? fromApi.am : fromApi.pm) : undefined
  if (!realItem && selectedDoctorRow.value) realItem = getItemByDateStr(selectedDoctorRow.value, selectedDate.value, session) as any
  
  const val = realItem ? realItem.patientNum : undefined
  return val !== undefined ? val : updatefrom.patientNum || 0
}

function updateFromBySelectedDate() {
  const row = selectedDoctorRow.value
  if (!row || !selectedDate.value) {
    updatefrom.consultationTime = ''
    updatefrom.num = 0
    updatefrom.patientNum = 0
    return
  }
  const slot = row.schedules[selectedDate.value]
  const prefer = (slot && slot.am) || (slot && slot.pm) || null
  updatefrom.consultationTime = prefer ? (prefer.consultationTime ?? '') : ''
  updatefrom.num = prefer ? (prefer.num ?? 0) : 0
  updatefrom.patientNum = prefer ? (prefer.patientNum ?? 0) : 0
}

// 按当前选中的日期，用该日期对应的 schedulingId 拉详情（严格按你的接口）
async function fetchSelectedDateDetail() {
  const row = selectedDoctorRow.value
  if (!row || !selectedDate.value) return
  const item = getPreferredItemForDate(row, selectedDate.value)
  const sid = item?.schedulingId
  if (sid) {
    await GetDoctorScheduling(sid)
  } else {
    // 如果当天没有 schedulingId（比如未排班），则清空或使用兜底
    dialogSchedules.value[selectedDate.value] = {}
    updateFromBySelectedDate()
  }
}
function submitSetSchedule() {
  const row = selectedDoctorRow.value
  const item = getPreferredItemForDate(row, selectedDate.value)
  const sid = item?.schedulingId
  
  // 获取当前选中日期的排班数据
  const amData = getItemByDateStr(row, selectedDate.value, 0)
  const pmData = getItemByDateStr(row, selectedDate.value, 1)
  
  // 优先使用上午数据，如果没有则使用下午数据
  const currentData = amData || pmData
  
  if (currentData) {
    // 数据反填到form中
    form.schedulingId = currentData.schedulingId || currentData.SchedulingId || 0
    form.doctorId = currentData.doctorId || currentData.DoctorId || ''
    form.depetmentId = currentData.depetmentId || currentData.DepetmentId || 0
    form.startDate = currentData.startDate || currentData.StartDate || ''
    form.consultationTime = currentData.consultationTime || currentData.ConsultationTime || ''
    form.num = currentData.num || currentData.Num || 0
    form.patientNum = currentData.patientNum || currentData.PatientNum || 0
    form.schedulingState = currentData.schedulingState || currentData.SchedulingState || 0
    form.session = currentData.session || currentData.Session || 0
    
    // 设置弹窗为修改模式
    logic.isadd = false
    logic.title = '修改医生排班信息'
    logic.isopen = true
  } else {
    // 如果没有数据，则跳转到设置页面
    router.push({
      path: '/DoctorSchedulingSettings',
      query: {
        doctorName: row?.doctorName || '',
        date: selectedDate.value,
        schedulingId: sid ? String(sid) : '',
      },
    })
  }
}

// 修改表格中的设置排班按钮点击事件
function openSetScheduleFromTable(row: any, day: Date, session: 0 | 1) {
  const currentData = getItem(row, day, session)
  if (currentData) {
    // 数据反填到form中
    form.schedulingId = currentData.schedulingId || currentData.SchedulingId || 0
    form.doctorId = currentData.doctorId || currentData.DoctorId || ''
    form.depetmentId = currentData.depetmentId || currentData.DepetmentId || 0
    form.startDate = currentData.startDate || currentData.StartDate || ''
    form.consultationTime = currentData.consultationTime || currentData.ConsultationTime || ''
    form.num = currentData.num || currentData.Num || 0
    form.patientNum = currentData.patientNum || currentData.PatientNum || 0
    form.schedulingState = currentData.schedulingState || currentData.SchedulingState || 0
    form.session = currentData.session || currentData.Session || 0
    
    // 设置弹窗为修改模式
    logic.isadd = false
    logic.title = '修改医生排班信息'
    logic.isopen = true
  } else {
    // 如果没有数据，则添加新记录
    form.schedulingId = 0
    form.doctorId = row.doctorId || ''
    form.depetmentId = 0
    form.startDate = ''
    form.consultationTime = ''
    form.num = 0
    form.patientNum = 0
    form.schedulingState = 0
    form.session = session
    
    // 设置弹窗为添加模式
    logic.isadd = true
    logic.title = '添加医生排班信息'
    logic.isopen = true
  }
}
function submitCloseBooking() {
  console.log('关闭预约', {
    doctorId: selectedDoctorRow.value?.doctorId,
    date: selectedDate.value,
    month: currentMonth.value,
  })
}

// 科室级联数据
const options = ref([])
const fetchDepartments = () => {
  dataRead.get("/Manage/Handle")
    .then(res => {
      options.value = res.data.data || []
    })
}
const props1 = {
  checkStrictly: true,
  emitPath: false,
}

//查询医生信息
const doctor=ref([{

  doctorId:'',
  doctorName:'',
}])

const ShowDoctor=()=>{
axios.get("http://localhost:5103/api/DoctorScheduling/GetDoctor").then(res=>{
if(res.data.code==200)
{
  doctor.value=res.data.data;
}

})

}



// 翻页参数
const page = reactive({
  PageIndex: 1,
  PageSize: 5, // 获取所有数据
  totalCount:0,
  pageCount:0,
  
})

//监听参数
watch(page,()=>{
  DoctorShow();
}
)




// 查询条件
const from = reactive({
  DoctorName: '',
  DepetmentId: '',
})
</script>

<style scoped>
.am-has { color: #f56c6c; font-weight: 500; }
.am-full { color: #e53935; font-weight: 600; }
.pm-rest { color: #909399; }
.day-cell { display: flex; flex-direction: column; gap: 6px; align-items: center; justify-content: center; padding: 4px 0; }
.session-row { display: inline-flex; align-items: center; gap: 6px; }
.session-row .num { font-size: 12px; }

/* 表头样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 0;
}

.week-navigation {
  display: flex;
  align-items: center;
  gap: 12px;
}

.week-range {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  min-width: 120px;
  text-align: center;
}

/* 时间段单元格样式 */
.session-cell {
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.session-cell:hover {
  background-color: #f5f7fa;
}

.record-selector {
  margin-top: 4px;
}

.record-selector .el-select {
  width: 100%;
}

.pagination-wrapper { display: flex; align-items: center; justify-content: flex-start; padding: 12px 12px 0; }
.pagination-wrapper :deep(.el-pagination.is-background) { padding: 4px 8px; border-radius: 8px; background: linear-gradient(180deg, #ffffff, #f5f7fa); border: 1px solid #ebeef5; box-shadow: 0 1px 6px rgba(0,0,0,0.08); }
.pagination-wrapper :deep(.el-pagination.is-background .el-pager li) { border-radius: 6px; }
.pagination-wrapper :deep(.el-pagination.is-background .el-pager li:hover) { background-color: #ecf5ff; }
.pagination-wrapper :deep(.el-pagination .el-select .el-input__wrapper) { min-width: 100px; }
.pagination-wrapper :deep(.el-pagination .el-input__inner) { text-align: center; }


.pagination-wrapper :deep(.el-pagination__body) { padding: 0; }
.dialog-body { display: flex; }
.dialog-left { width: 260px; background: #ff8a3d; color: #fff; padding: 20px; }
.doctor-title { font-size: 18px; font-weight: 600; margin-bottom: 16px; }
.date-title { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
.weekday { opacity: 0.95; margin-bottom: 12px; }
.section { margin: 8px 0 16px; }
.section-title { font-size: 16px; font-weight: 600; margin-bottom: 8px; }
.kv { margin: 4px 0; }
.dialog-right { flex: 1; padding: 16px 20px; }
.top-actions { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
.flex-spacer { flex: 1; }
.month-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 12px; }
.grid-day { background: #f7f9fc; border: 1px solid #edf2f7; border-radius: 8px; padding: 14px 10px; text-align: center; cursor: pointer; }
.grid-day .day-num { font-size: 22px; font-weight: 600; margin-bottom: 6px; }
.grid-day .day-label { font-size: 14px; color: #3a7afe; }
.grid-day.rest .day-label { color: #909399; }
.grid-day.none { color: #c0c4cc; }
.grid-day.selected { background: #1063ff; color: #fff; }
.grid-day.selected .day-label { color: #fff; }
</style>
